from urllib.request import *
from urllib.parse import *
from fake_useragent import *


def get_html(url):
    headers = {
        "User-agent": UserAgent().chrome
    }
    request = Request(url, headers=headers)
    response = urlopen(request)
    # print(response.read().decode())
    return response.read()


def save_html(filename, html_bytes):
    with open(filename, "wb") as f:
        f.write(html_bytes)


def main():
    content = input("请输入要下载的内容：")
    num = input("请输入要下载多少页：")
    base_url = "https://tieba.baidu.com/f?"
    for pn in range(int(num)):
        args = {
            "kw": content,
            "pn": pn * 50
        }
        filename = "第" + str(pn + 1) + "页.html"
        print("正在下载" + filename)
        html_bytes = get_html(f"{base_url}{urlencode(args)}")
        save_html(filename, html_bytes)
        print(filename+"下载完成")


if __name__ == '__main__':
    main()
